/*
  学习目标：本地缓存
 
*/

import { Footer } from './components/Footer';
import { Header } from './components/Header';
import { Main } from './components/Main';
import './styles/base.css';
import './styles/index.css';
import { useState } from 'react';
import { useEffect } from 'react';

export default function App() {
  const [type, setType] = useState('all');
  const [list, setList] = useState([]);

  // 💥注意：先写挂载， 后写更新
  // 2. 从缓存中取出数据，作为list的值 使用useEffect在挂载后，获取数据
  useEffect(() => {
    const localList = JSON.parse(localStorage.getItem('todo-list') || '[]');
    setList(localList);
  }, []);

  // 1. 监听数据的变化, 获取更新后的值useEffect
  // 更新挂载而合一
  useEffect(() => {
    localStorage.setItem('todo-list', JSON.stringify(list));
  }, [list]);

  const handleDelById = (id) => {
    const newList = list.filter((item) => item.id !== id);
    setList(newList);
  };

  const handleClearDone = () => {
    const newList = list.filter((item) => !item.isDone);
    setList(newList);
  };

  const handleUpdateById = (id) => {
    const newList = list.map((item) => ({
      ...item,
      isDone: item.id === id ? !item.isDone : item.isDone,
    }));

    setList(newList);
  };

  const handleAdd = (task) => {
    const newList = [{ isDone: false, id: Date.now(), task }, ...list];
    setList(newList);
  };

  const handleUpdateType = (type) => {
    setType(type);
  };

  const showList = list.filter((item) => {
    if (type === 'all') return true;
    if (type === 'active') return !item.isDone;
    return item.isDone;
  });

  const handleCheckAll = (checked) => {
    const newList = list.map((item) => ({ ...item, isDone: checked }));
    setList(newList);
  };

  const isAll = list.length ? list.every((item) => item.isDone) : false;

  return (
    <section className="todoapp">
      <Header handleAdd={handleAdd} />
      <Main
        handleCheckAll={handleCheckAll}
        isAll={isAll}
        handleUpdateById={handleUpdateById}
        handleDelById={handleDelById}
        list={showList}
      />
      <Footer type={type} handleClearDone={handleClearDone} handleUpdateType={handleUpdateType} />
    </section>
  );
}
